#include <REGX52.H>

/**
 * 菜单控制LED
 * 1. 正向流水灯
 * 2. 反向流水灯
 * 3. 正向计时功能
 * 4. 倒计时功能
 *
 * 功能模式按键，菜单前进按键，菜单后退按键
 */

// 定义按钮
sbit BTN1 = P3 ^ 0;// 模式按键
sbit BTN2 = P3 ^ 1;// 前进
sbit BTN3 = P3 ^ 2;// 后退

// 定义状态
#define FORWARDFLOWLIGHT 0
#define REVERSEFLOWLIGHT 1
#define COUNTUP 2
#define COUNTDOWN 3


unsigned char current = FORWARDFLOWLIGHT;// 默认状态
unsigned char count = 0;
unsigned char number1 = 0x00;
unsigned char number2 = 0xff;
unsigned char last_mode = 0xff;// 上一次的模式
unsigned char temp;

// 声明函数
void delay_ms(unsigned int ms);
void forward_FlowLight();
void reverse_FlowLight();
void count_up();
void count_down();

// 主函数
void main()
{
    P2 = 0xff; // 所有LED熄灭
    count = 0;

    while(1)
    {
        // 按键1：切换模式
        if(BTN1 == 0)
        {
            delay_ms(20); // 消抖
            if(BTN1 == 0)
            {
                current++;
                if(current > COUNTDOWN) current = FORWARDFLOWLIGHT;
                while(BTN1 == 0); // 等待松手
            }
        }

        // 按键2：菜单前进
        if(BTN2 == 0)
        {
            delay_ms(20);
            if(BTN2 == 0)
            {
                current++;
                if(current > COUNTDOWN) current = FORWARDFLOWLIGHT;
                while(BTN2 == 0); // 等待松手
            }
        }

        // 按键3：菜单后退
        if(BTN3 == 0)
        {
            delay_ms(20);
            if(BTN3 == 0)
            {
                if(current == FORWARDFLOWLIGHT)
                    current = COUNTDOWN;
                else
                    current--;
                while(BTN3 == 0); // 等待松手
            }
        }

        // 如果模式发生变化则进行重置
        if(current != last_mode) {
            last_mode = current;
            number1 = 0x00;
            number2 = 0xff;
        }

        // 根据当前状态执行相应功能
        switch(current)
        {
            case FORWARDFLOWLIGHT:
                forward_FlowLight();
                break;
            case REVERSEFLOWLIGHT:
                reverse_FlowLight();
                break;
            case COUNTUP:
                count_up();
                break;
            case COUNTDOWN:
                count_down();
                break;
        }
    }
}

//延迟函数
void delay_ms(unsigned int ms)
{
    unsigned int i, j;
    for (i = 0; i < ms; i++)
    {
        for (j = 0; j < 123; j++)
            ;
    }
}

//正向流水灯
void forward_FlowLight()
{
    static unsigned char temp1 = 0x80; 
    P2 = ~temp1;
    temp1 = temp1 >> 1;
    // 如果移到最后一位，重新从最高位开始
    if(temp1 == 0) 
    temp1 = 0x80;
    delay_ms(200);  
}

//反向流水灯
void reverse_FlowLight()
{
    static unsigned char temp2 = 0x01; 
    P2 = ~temp2;
    temp2 = temp2 << 1;
    if(temp2 == 0) 
    temp2 = 0x01;
    delay_ms(200);  
}

//计数
void count_up()
{
    P2 = ~number1;  // 取反显示
    number1++;
    delay_ms(200);
}

//倒计时
void count_down()
{
    P2 = ~number2;  // 取反显示
    if(number2 == 0)
        number2 = 0xff;
    else
        number2--;
    delay_ms(200);//如果说延迟过久的话那么这样就要按下很多次
}
